#!/usr/bin/env node

/**
 * 强制删除远程数据库中的所有表
 */

const mysql = require('mysql2/promise');

const remoteDbConfig = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    charset: 'utf8mb4'
};

async function forceDropAllTables() {
    let connection;
    
    try {
        console.log('🔌 连接远程数据库...');
        connection = await mysql.createConnection(remoteDbConfig);
        console.log('✅ 远程数据库连接成功');
        
        // 禁用外键检查
        console.log('🔧 禁用外键检查...');
        await connection.execute('SET FOREIGN_KEY_CHECKS = 0');
        
        // 直接执行删除所有表的SQL
        console.log('🗑️ 执行删除所有表的SQL...');
        
        // 获取所有表名并生成删除语句
        const [tables] = await connection.execute(`
            SELECT table_name 
            FROM information_schema.tables 
            WHERE table_schema = ? AND table_type = 'BASE TABLE'
        `, [remoteDbConfig.database]);
        
        if (tables.length > 0) {
            // 构建删除所有表的SQL语句
            const dropStatements = tables.map(table => `DROP TABLE IF EXISTS \`${table.table_name}\``);
            const dropSQL = dropStatements.join('; ');
            
            console.log(`📊 准备删除 ${tables.length} 个表`);
            console.log('🔍 表名列表:');
            tables.forEach((table, index) => {
                console.log(`   ${index + 1}. ${table.table_name}`);
            });
            
            // 执行删除
            await connection.execute(dropSQL);
            console.log('✅ 所有表删除完成');
        } else {
            console.log('✅ 数据库中没有表需要删除');
        }
        
        // 重新启用外键检查
        console.log('🔧 重新启用外键检查...');
        await connection.execute('SET FOREIGN_KEY_CHECKS = 1');
        
        // 验证删除结果
        console.log('🔍 验证删除结果...');
        const [remainingTables] = await connection.execute(`
            SELECT COUNT(*) as count 
            FROM information_schema.tables 
            WHERE table_schema = ? AND table_type = 'BASE TABLE'
        `, [remoteDbConfig.database]);
        
        console.log(`📊 剩余表数: ${remainingTables[0].count} 个`);
        
        if (remainingTables[0].count === 0) {
            console.log('\n🎉 所有表已成功删除！数据库已清空。');
        } else {
            console.log('\n⚠️ 仍有表未删除。');
        }
        
    } catch (error) {
        console.error('❌ 删除表过程中发生错误:', error.message);
        throw error;
    } finally {
        if (connection) {
            await connection.end();
            console.log('\n🔌 数据库连接已关闭');
        }
    }
}

// 运行删除
async function main() {
    console.log('🎯 强制删除数据库表脚本');
    console.log('   功能：强制删除远程数据库中的所有表\n');
    
    await forceDropAllTables();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 删除脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = { forceDropAllTables };
